package com.lzx.adx.report.controller.v1.honor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.honnor.HonorRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 荣耀端对接夸克产品
 */
@RequestMapping("/honor/jdjr")
@RestController
@Slf4j
public class HonorJdjrController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(HonorRequest HonorRequest, HttpServletRequest request) {
        log.info("接收到荣耀到京东金融的请求参数为{}", JsonUtils.toJsonString(HonorRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(HonorRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(HonorRequest));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(HonorRequest.getDspId());
        String finalUrl = UrlUtil.handJdjrReplace(reportDTO, accountDTO);
        log.info("账号为{}完整的荣耀到京东金融请求地址为{}", HonorRequest.getDspId(), finalUrl);
        //2.2调用夸克上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{}完整的荣耀到京东金融上报的接口，响应的结果为{}", HonorRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }

    /**
     * 夸克的回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String click_id, String conv_type, String conv_ts) throws Exception {
        log.info("接收了荣耀京东金融回调信息，请求流水号{},回调类型为{}，回调时间{}", click_id, conv_type, conv_ts);
        if (StringUtils.isBlank(conv_type) || StringUtils.isBlank(click_id)) {
            log.info("接收了荣耀京东金融回调信息请求参数异常，event_type{},event_time{},click_id{}", conv_type, conv_ts, click_id);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        String time = String.valueOf(System.currentTimeMillis());
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("辉煌明天-闲鱼回传流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(conv_type);
        if (StringUtils.isBlank(eventType)){
            log.info("账号id{}请求Id:{}事件类型:{}荣耀京东金融回传类型不匹配,不做回传",reportDTO.getDspId(),requestId,conv_type);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(conv_type);
        reportDTO.setResultTime(time);
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,conv_type);
        Double per = jsonObject.getDouble("per");
        if (Objects.nonNull(per)) {
            if(!AdPerUtil.randomPer(per)) {
                log.info("账户{}流水号{}超出了比例,不做回传", reportDTO.getDspId(), reportDTO.getBizRequestId());
                return ResponseEntity.ok(new Result());
            }
        }
        HonorRequest honorRequest = JsonUtils.parseObject(reportDTO.getExtend(), HonorRequest.class);
        String sspApiUrl = accountDTO.getSspApiUrl();
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("trackId", honorRequest.getTrackId());
        paramsReq.put("conversionId", eventType);
        paramsReq.put("conversionTime", time);
        paramsReq.put("advertiserId", honorRequest.getAdvertiserId());
        String finalUrl = sspApiUrl + "?" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);
        log.info("dspId:{},请求Id{}京东金融回传给荣耀的请求完整地址为{}", reportDTO.getDspId(), requestId, finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("dspId:{},请求Id{}京东金融回传给荣耀的结果为{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


    

}
